<?php

namespace App\Http\Controllers\Finance;

use App\Common\SDK\Facade\FenZhangTong;
use App\Common\SDK\Facade\ZhiLing;
use App\Http\Controllers\Controller;
use App\Models\FinanceAdministrator;
use App\Models\SmsLog;
use App\Services\Authorization;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;

class AuthController extends Controller
{
    public function store(Request $request)
    {
        if (!$token = Auth::guard('finance')->attempt($request->only(['account', 'password']))) {
            $this->response->errorUnauthorized(trans('auth.incorrect'));
        }

        /** @var FinanceAdministrator $admin */
        $admin = Auth::guard('finance')->authenticate($token);

        // 发送验证码
        $uuid = Str::uuid()->toString();
        Redis::setex('finance_login_sms_captcha_' . $uuid, 15 * 60, json_encode(array_merge(['phone' => $admin['phone']], $request->only(['account', 'password']))));

        $code = app()->environment(['staging', 'local']) ? 123456 : random_int(100000, 999999); // 测试开发环境固定
        $content = sprintf('您的验证码是%d', $code);
        $expiredAt = Carbon::now()->addMinutes(15)->timestamp;
        SmsLog::create([
            'phone' => $admin['phone'],
            'content' => $content,
            'properties' => [
                'code' => $code,
                'expired_at' => $expiredAt,
                'uuid' => $uuid,
            ],
            'type' => SmsLog::TYPE_FINANCE_LOGIN_SMS_CAPTCHA,
        ]);

        ZhiLing::sms([
            'phones' => $admin['phone'],
            'sms_body' => $content,
            'sms_sign' => env('ZHI_LING_SMS_SIGN', '省到家'),
        ]);

        return $this->response->created(null, ['uuid' => $uuid, 'expired_at' => $expiredAt]);
    }

    public function confirm(Request $request)
    {
        $loginInfo = Redis::get('finance_login_sms_captcha_' . $request->get('uuid'));
        if (empty($loginInfo)) {
            $this->response->errorBadRequest('验证码错误或已失效');
        }
        $loginInfo = json_decode($loginInfo, true);
        try {
            $smsLog = SmsLog::query()
                ->where('phone', $loginInfo['phone'])
                ->orderBy('created_at', 'desc')
                ->firstOrFail()
                ->toArray();
        } catch (ModelNotFoundException $e) {
            $this->response->errorBadRequest('验证码错误或已失效');
        }
        if (!((int) $smsLog['properties']['code'] === (int) $request->get('sms_captcha')
            && $smsLog['properties']['uuid'] === $request->get('uuid')
            && Carbon::now()->isBefore(Carbon::parse($smsLog['properties']['expired_at'])))) {
            $this->response->errorBadRequest('验证码错误或已失效');
        }

        if (!$token = Auth::guard('finance')->attempt(Arr::only($loginInfo, ['account', 'password']))) {
            $this->response->errorUnauthorized(trans('auth.incorrect'));
        }

        return $this->response->created(null, (new Authorization($token))->toArray());
    }

    public function destory()
    {
        Auth::logout();

        return $this->response->noContent();
    }

    public function info()
    {
        try {
            $user = Auth::user()->toArray();
        } catch (\Exception $e) {
            $this->response->errorForbidden();
        }

        $subAccountFundInquiry = FenZhangTong::subAccountFundInquiry(['acctType' => \App\Common\SDK\Domain\FenZhangTong::SUB_ACCOUNT_TYPE_ORDINARY_CAPITAL_SPLIT]);
        Arr::forget($subAccountFundInquiry, ['retCode', 'retMsg', 'signData']);

        return $this->response->array(array_merge($user, ['balance' => $subAccountFundInquiry]));
    }

    public function operateSms()
    {
        $phone = Auth::user()['phone'];
        if (empty($phone)) {
            $this->response->errorBadRequest('当前账户手机号为空');
        }

        // 发送验证码
        $uuid = Str::uuid()->toString();

        $code = app()->environment(['staging', 'local']) ? 123456 : random_int(100000, 999999); // 测试开发环境固定
        $content = sprintf('您的验证码是%d', $code);
        $expiredAt = Carbon::now()->addMinutes(15)->timestamp;
        SmsLog::create([
            'phone' => $phone,
            'content' => $content,
            'properties' => [
                'code' => $code,
                'expired_at' => $expiredAt,
                'uuid' => $uuid,
            ],
            'type' => SmsLog::TYPE_FINANCE_OPERATE_SMS_CAPTCHA,
        ]);

        ZhiLing::sms([
            'phones' => $phone,
            'sms_body' => $content,
            'sms_sign' => env('ZHI_LING_SMS_SIGN', '省到家'),
        ]);

        // 配合中间件验证使用
        return $this->response->noContent();
    }
}
